#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库基础配置
定义SQLAlchemy实例和基础模型类
"""

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timezone
from sqlalchemy import Column, Integer, DateTime, String
import uuid

# 创建SQLAlchemy实例
db = SQLAlchemy()

class BaseModel(db.Model):
    """
    基础模型类
    包含所有表的公共字段
    """
    __abstract__ = True
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()), comment='主键UUID')
    created_at = Column(DateTime, default=datetime.now(timezone.utc), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc), nullable=False, comment='更新时间')
    
    def to_dict(self):
        """
        将模型对象转换为字典
        
        Returns:
            dict: 模型数据字典
        """
        result = {}
        for column in self.__table__.columns:
            value = getattr(self, column.name)
            if isinstance(value, datetime):
                value = value.isoformat()
            result[column.name] = value
        return result
    
    def __repr__(self):
        return f'<{self.__class__.__name__}(id={self.id})>'